const path = require('path');
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const rimraf = require('rimraf');
const nodeExternals = require('webpack-node-externals');

/**
 * 此处加插件代码打包定义;
 * plugins.cli.ts 里面加命令行定义;
 * package.json 里面 postinstall加 moudle 依赖install;
 */
const pluginsCfg = [
	{
		entry: {
			resgenrator: './res_genrator/src/index.ts',
		},
		define: {
			develop: {
				RES_CFG_PATH: '"../../../assets/genrator_cfg"'
			},
			release: {
				RES_CFG_PATH: '"../../../assets/genrator_cfg"'
			}
		},
		root: "res_genrator"
	},
	{
		entry: {
			resToolClass: './res_genrator/src/resToolClass.ts',
		},
		define: {
			develop: {
				RES_CFG_PATH: '"../../../assets/genrator_cfg"'
			},
			release: {
				RES_CFG_PATH: '"../../../assets/genrator_cfg"'
			}
		},
		root: "res_genrator"
	}
];

const PLUGIN_COMMON = {
	target: 'node',
	context: path.join(__dirname, 'plugins'),
	resolve: {
		extensions: ['*', '.js', '.jsx', '.ts', '.tsx'],
		modules: [
			path.join(__dirname, './plugins')
		]
	},
	output: {
		filename: '[name].js',
		path: __dirname + '/plugins/out',
		devtoolModuleFilenameTemplate: 'webpack:///../plugins/[resource-path]',
		libraryTarget: "commonjs"
	},
	externals: [],
	module: {
		rules: [
			{
				test: /\.ts(x?)$/,
				use: {
					loader: 'ts-loader',
					options: {
						configFile: path.resolve(__dirname, "plugins/tsconfig.json")
					}
				},
				exclude: /node_modules/
			}
		]
	},
	plugins: []
};

module.exports = (mode) => {

	const hasCleanDir = {};
	class MyWebpackCleanPlugin {
		apply(compiler) {
			if (!compiler.options.output || !compiler.options.output.path) {
				return;
			}
			this.outputPath = compiler.options.output.path;
			compiler.hooks.emit.tap('MyWebpackCleanPlugin', () => {
				if (hasCleanDir[this.outputPath]) {
					return;
				}
				rimraf.sync(this.outputPath);
				hasCleanDir[this.outputPath] = true;
			});
		}
	}

	var extra = mode == 'development' ? {
		mode: 'development',
		devtool: 'inline-source-map'
	} : {
		mode: 'production'
	};
	return pluginsCfg.map(data => {
		const res = merge(PLUGIN_COMMON, data, extra);
		if (!!res.root) {
			res.externals.push(
				nodeExternals({
					modulesFromFile: {
						fileName: `./plugins/${res.root}/package.json`,
						includeInBundle: ['devDependencies'],
						excludeFromBundle: ['dependencies']
					}
				})
			);
			res.output.path = path.resolve(__dirname, `./plugins/${res.root}/out`);
			res.plugins.push(
				new MyWebpackCleanPlugin()
			);
			delete res.root;
		}
		if (!!res.define) {
			res.plugins.push(
				new webpack.DefinePlugin(mode == 'development' ? res.define.develop : res.define.release)
			);
			delete res.define;
		}
		return res;
	});
}
